const dotenv = require('./config/dotenv')
const config = require('./config')

const Koa = require('koa')
const app = new Koa()

const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')
const swagger = require('./routes/swagger')

const cors = require('koa-cors')

const routes = require('./routes')
const {STATUS_CODES} = require('http')

const authServer = require('./components/auth/index')

// error handler
onerror(app, {
  json(err) {
    const error = err.originalError?.error || err.error || STATUS_CODES[err.status]
    const error_description = err.message
    const error_details = err.details
    this.body = {error, error_description, error_details}
  }
})

// middlewares
app.use(bodyparser())
  .use(json())
  .use(logger())
  .use(require('koa-static')(process.cwd() + '/public'))
  .use(views(path.join(__dirname, '/views'), {
    options: {settings: {views: path.join(__dirname, 'views')}},
    map: {'njk': 'nunjucks'},
    extension: 'njk'
  }))
  .use(swagger({
    routePrefix: '/swagger',
    swaggerOptions: {
      url: '/swagger.json'
    }
  }, app))
  .use(cors({
    credentials: true
  }))
  .use(authServer(app))

routes.forEach(middleware => app.use(middleware))
app.on('error', (err, ctx) => {
  console.error(err)
})

module.exports = app.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})
